package com.jumi.microservice.service.logistics.express;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jumi.microservice.common.utils.HttpClientUtils;
import com.jumi.microservice.dto.logistics.Logistics;
import com.jumi.microservice.dto.logistics.LogisticsSearchRequest;
import com.jumi.microservice.dto.logistics.LogisticsSearchResponse;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author by mazhao
 * 德邦快递
 * @Classname DepponExpress
 * @Description TODO
 * @Date 2020/8/21 14:33
 */
@Service
public class DepponExpress extends ResponseController  implements Express {

    private static final Logger log = LoggerFactory.getLogger(DepponExpress.class);

    @Resource
    HttpClientUtils httpClientUtils;

    private static String url = "http://dpapi.deppon.com/dop-interface-sync/standard-query/newTraceQuery.action";
    private static String companyCode = "EWBJMDZSWYXGS";
    private static String appKey = "25ede5417946b1177ef15efe56c2526c";

    @Override
    public String expressCode() {
        return "DBL";
    }

    @Override
    public LogisticsSearchResponse logisticsSearch(LogisticsSearchRequest request) {
        JSONArray jsonArray = null;
        log.info("德邦快递查询参数[{}]", JSON.toJSONString(request));
        try {
            //拼接请求头
            Map<String,String> headers = new HashMap<>(1);
            headers.put("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
            //组建数据格式
            String timestamp = String.valueOf(System.currentTimeMillis());
            String params = "{\"mailNo\":\""+request.getLogisticsNo()+"\"}";
            String digest = Base64.encodeBase64String(DigestUtils.md5Hex(params+appKey+timestamp).getBytes());
            String requestData = "params="+params+"&digest="+digest+"&timestamp="+timestamp+"&companyCode="+companyCode;
            //发送请求并接受返回
            String res = httpClientUtils.post(url, requestData,headers);
            //处理返回结果
            log.info("请求返回结果[{}]",res);
            JSONObject json = JSONObject.parseObject(res);
            jsonArray = json.getJSONObject("responseParam").getJSONArray("trace_list");
        } catch (Exception e) {
            log.error("德邦快递查询出错[{}]",e.getMessage());
        }
        LogisticsSearchResponse logisticsSearchResponse = checkResult(jsonArray,request);
        return controller(logisticsSearchResponse,jsonArray,"description","time");
    }
}
